package cn.hsp.chargemagic

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter

/**
 * @author 花生皮编程(CSDN、简书、掘金、今日头条、微信公众号、抖音、快手、B站、西瓜视频)
 * @关于作者 https://juejin.cn/post/7002792005688360968
 */
class BatteryListener(private val mContext: Context) {
    private val receiver: BatteryBroadcastReceiver?
    private var mBatteryStateListener: BatteryStateListener? = null
    fun register(listener: BatteryStateListener?) {
        mBatteryStateListener = listener
        if (receiver != null) {
            val filter = IntentFilter()
            filter.addAction(Intent.ACTION_BATTERY_CHANGED)
            filter.addAction(Intent.ACTION_BATTERY_LOW)
            filter.addAction(Intent.ACTION_BATTERY_OKAY)
            filter.addAction(Intent.ACTION_POWER_CONNECTED)
            filter.addAction(Intent.ACTION_POWER_DISCONNECTED)
            mContext.registerReceiver(receiver, filter)
        }
    }

    fun unregister() {
        if (receiver != null) {
            mContext.unregisterReceiver(receiver)
        }
    }

    private inner class BatteryBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                Intent.ACTION_BATTERY_CHANGED -> if (mBatteryStateListener != null) {
                    mBatteryStateListener!!.onStateChanged()
                }
                Intent.ACTION_BATTERY_LOW -> if (mBatteryStateListener != null) {
                    mBatteryStateListener!!.onStateLow()
                }
                Intent.ACTION_BATTERY_OKAY -> if (mBatteryStateListener != null) {
                    mBatteryStateListener!!.onStateOkay()
                }
                Intent.ACTION_POWER_CONNECTED -> if (mBatteryStateListener != null) {
                    mBatteryStateListener!!.onStatePowerConnected()
                }
                Intent.ACTION_POWER_DISCONNECTED -> if (mBatteryStateListener != null) {
                    mBatteryStateListener!!.onStatePowerDisconnected()
                }
            }
        }
    }

    interface BatteryStateListener {
        fun onStateChanged()
        fun onStateLow()
        fun onStateOkay()
        fun onStatePowerConnected()
        fun onStatePowerDisconnected()
    }

    init {
        receiver = BatteryBroadcastReceiver()
    }
}